package com.jeecg.p3.system.order.web;

import com.jeecg.p3.base.util.ComCode;
import com.jeecg.p3.base.util.DateUtil;
import com.jeecg.p3.base.util.StringUtils;
import com.jeecg.p3.system.advisor.entity.StudyAdviser;
import com.jeecg.p3.system.advisor.service.StudyAdvService;
import com.jeecg.p3.system.base.BaseController;
import com.jeecg.p3.system.entity.Product;
import com.jeecg.p3.system.order.entity.CourseOrder;
import com.jeecg.p3.system.order.entity.ProductDetails;
import com.jeecg.p3.system.order.service.CourseOrderService;
import com.jeecg.p3.system.order.service.ProductDetailsService;
import com.jeecg.p3.system.poster.entity.AdvisorCoupon;
import com.jeecg.p3.system.poster.entity.GradesNum;
import com.jeecg.p3.system.poster.entity.ProductCoupon;
import com.jeecg.p3.system.poster.entity.ScanCodeNum;
import com.jeecg.p3.system.poster.service.AdvisorCouponService;
import com.jeecg.p3.system.poster.service.GradesNumService;
import com.jeecg.p3.system.poster.service.ProductCouponService;
import com.jeecg.p3.system.service.ProductService;
import com.jeecg.p3.system.vo.LoginUser;
import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.util.SystemTools;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.utils.common.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping("/system/back/order/courseOrder")
public class CourseOrderController extends BaseController {

    @Autowired
    private CourseOrderService service;
    @Autowired
    private StudyAdvService studyAdvService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductCouponService productCouponService;
    @Autowired
    private AdvisorCouponService advisorCouponService;
    @Autowired
    private GradesNumService gradesNumService;
    @Autowired
    private ProductDetailsService productDetailsService;

    /**
     * 查询顾问绩效
     */
    @RequestMapping(value = "/toMyGrades",method ={RequestMethod.GET, RequestMethod.POST})
    public void toMyGrades(@ModelAttribute CourseOrder query, HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                             @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize)  throws Exception{
        VelocityContext velocityContext = new VelocityContext();
        String viewName = "system/back/app/my_grade.html";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    @ResponseBody
    @RequestMapping(value = "/findMyGrades",method ={RequestMethod.GET, RequestMethod.POST})
    public Map<String, Object> findMyGrades(@ModelAttribute CourseOrder query,
        HttpServletRequest request, HttpServletResponse response, String type,
        @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
        @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize)
    {
        if(ComCode.day.equals(type)) {
            query.setCreateDate(DateUtil.dateToString(new Date()));
        } else if(ComCode.week.equals(type)) {
            query.setCreateDate(DateUtil.getPastDate(7));
        } else if(ComCode.month.equals(type)) {
            query.setCreateDate(DateUtil.getPastDate(30));
        }
        LoginUser u = getCurrentUser(request);
        Map<String, Object> map = new HashMap<>();
        PageQuery<CourseOrder> pageQuery = new PageQuery<>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        StudyAdviser studyAdviser = studyAdvService.findByUserNumber(u.getUserId());
        query.setStudyAdvId(studyAdviser.getId());
        query.setPayStatus(2);//查询支付成功订单
        pageQuery.setQuery(query);
        map.put("pageInfos", service.queryPageList(pageQuery));
        return map;
    }

    /**
     * 获取当前时间的交易量
     * @param request
     * @param response
     */
    public void getDataByDate(HttpServletRequest request, HttpServletResponse response) {
        List<StudyAdviser> studyAdvisers = studyAdvService.findByParam(new StudyAdviser());//顾问列表
        //课程优惠券列表（没门课程只有一张优惠券）
        List<ProductCoupon> productCoupons =  productCouponService.findByParam(new ProductCoupon());
        //根据顾问和课程优惠券去查询顾问唯一优惠券，如果优惠券为空，说明顾问没有该课程权限，则该课程交易量为0
        List<String> titles = new ArrayList<>();
        titles.add("顾问");
        for(ProductCoupon p: productCoupons) {
            titles.add(p.getProductName());
        }
        titles.add("总数");
        for(StudyAdviser stu: studyAdvisers) {
            Map<String, Object> map = new HashMap<>();
            map.put("stuName", stu.getRealName());
            Integer productSumNum = 0;
            for(ProductCoupon p: productCoupons) {
                AdvisorCoupon advisorCoupon = new AdvisorCoupon();
                advisorCoupon.setStudyAdvId(stu.getId());
                advisorCoupon.setProductCouponId(p.getId());
                AdvisorCoupon advCoupon= advisorCouponService.findByParams(advisorCoupon);
                if(advCoupon == null) {
                    map.put("", "");
                } else {

                }
            }
        }
    }

    /**
     * 跳转到业绩走势界面
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value="/toGradesIcon.do",method = {RequestMethod.GET,RequestMethod.POST})
    public void myList(HttpServletRequest request, HttpServletResponse response) throws Exception {
        VelocityContext velocityContext = new VelocityContext();
        String viewName = "system/back/order/grades_num_icon.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     * 业绩走势图
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/gradesData",method = {RequestMethod.GET,RequestMethod.POST})
    public AjaxJson gradesData() {
        AjaxJson j = new AjaxJson();
        String lastMonth = DateUtil.getLastMonthInToday();//获取上个月
        String lastEndDate = DateUtil.dateToString(DateUtil.getLastDayInMonth(lastMonth));//上月最后一天
        String lastStartDate = DateUtil.dateToString(DateUtil.getFirstDayFromMonth(lastEndDate));//获取上月第一天
        String nowDate = DateUtil.dateToString(new Date());//当前日期
        String nowStartDate = DateUtil.dateToString(DateUtil.getFirstDayFromMonth(nowDate));//当月开始时间
        GradesNum lastParam = new GradesNum(lastStartDate, lastEndDate);//上月参数
        GradesNum nowParam = new GradesNum(nowStartDate, nowDate);//当月参数
        List<GradesNum> lastList = gradesNumService.findByParam(lastParam);
        List<GradesNum> nowList = gradesNumService.findByParam(nowParam);
        List<String> lastNum = new ArrayList<>();
        for(GradesNum gn: lastList) {
            if(gn != null && StringUtils.isNotEmpty(gn.getNum())) {
                lastNum.add(gn.getNum());
            }
        }
        List<String> nowNum = new ArrayList<>();
        for(GradesNum gn: nowList) {
            if(gn != null && StringUtils.isNotEmpty(gn.getNum())) {
                nowNum.add(gn.getNum());
            }
        }
        ProductDetails param = new ProductDetails();
        param.setCreateDate(nowDate);
        nowNum.add(productDetailsService.count(param).toString());
        String[] lastArray = lastNum.toArray(new String[0]);
        String[] nowArray = nowNum.toArray(new String[0]);
        Map<String, Object> map = new HashMap<>();
        map.put("lastArray", lastArray);
        map.put("nowArray", nowArray);
        j.setObj(map);

        return j;
    }

    /**
     * 跳转到业绩管理界面
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value="/toGrades.do",method = {RequestMethod.GET,RequestMethod.POST})
    public void gradesList(HttpServletRequest request, HttpServletResponse response,@ModelAttribute CourseOrder query,
        @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
        @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception {
        VelocityContext velocityContext = new VelocityContext();
        PageQuery<CourseOrder> pageQuery = new PageQuery<>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        query.setPayStatus(2);//支付成功的订单
        pageQuery.setQuery(query);
        velocityContext.put("courseOrder",query);
        velocityContext.put("pageInfos", SystemTools.convertPaginatedList(service.queryPageList(pageQuery)));
        List<Product> lstProduct = productService.find();
        velocityContext.put("lstProduct",lstProduct);
        List<StudyAdviser> advisers = studyAdvService.findByParam(new StudyAdviser());
        velocityContext.put("advisers", advisers);
        List<Map<String, Object>> sumList = service.findCountByParam(pageQuery);
        velocityContext.put("sumList", sumList);
        if(StringUtils.isNotEmpty(query.getProductGroup()) && StringUtils.isNotEmpty(query.getStudyAdvGroup())) {
            velocityContext.put("isAll", true);
            Integer sumCount = 0;
            Double sumMoney = 0.00;
            if(sumList != null) {
                for(Map<String, Object> m: sumList) {
                    Object count = m.get("counts");
                    Object sumMon = m.get("sumMoney");
                    if(count != null) {
                        sumCount = sumCount + Integer.valueOf(count.toString());
                    }
                    if(sumMon != null) {
                        sumMoney = sumMoney + Double.valueOf(sumMon.toString());
                    }
                }
            }
            velocityContext.put("sumCount", sumCount);
            velocityContext.put("sumMoney", sumMoney);
        } else if(StringUtils.isNotEmpty(query.getProductGroup()) && StringUtils.isEmpty(query.getStudyAdvGroup())) {
            velocityContext.put("isProduct", true);
            Integer sumCount = 0;
            Double sumMoney = 0.00;
            if(sumList != null) {
                for(Map<String, Object> m: sumList) {
                    Object count = m.get("counts");
                    Object sumMon = m.get("sumMoney");
                    if(count != null) {
                        sumCount = sumCount + Integer.valueOf(count.toString());
                    }
                    if(sumMon != null) {
                        sumMoney = sumMoney + Double.valueOf(sumMon.toString());
                    }
                }
            }
            velocityContext.put("sumCount", sumCount);
            velocityContext.put("sumMoney", sumMoney);
        } else if(StringUtils.isNotEmpty(query.getStudyAdvGroup()) && StringUtils.isEmpty(query.getProductGroup())) {
            velocityContext.put("isStudy", true);
            Integer sumCount = 0;
            Double sumMoney = 0.00;
            if(sumList != null) {
                for(Map<String, Object> m: sumList) {
                    Object count = m.get("counts");
                    Object sumMon = m.get("sumMoney");
                    if(count != null) {
                        sumCount = sumCount + Integer.valueOf(count.toString());
                    }
                    if(sumMon != null) {
                        sumMoney = sumMoney + Double.valueOf(sumMon.toString());
                    }
                }
            }
            velocityContext.put("sumCount", sumCount);
            velocityContext.put("sumMoney", sumMoney);
        } else {
            velocityContext.put("isNull", true);
        }
        String viewName = "system/back/order/grades_list.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }
}
